package com.situ.firmadmin.interceptor;

import com.situ.firmadmin.util.JwtUtil;
import com.situ.firmadmin.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//Interceptor 拦截器
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

   /* private IUserService userService;

    private IAuthService authService;

    public LoginInterceptor(IUserService userService, IAuthService authService) {
        this.userService = userService;
        this.authService = authService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断用户有没有登录
        //2.如果登录了就放行，可以访问后台资源
        //3.如果没有登录，跳转到登录界面
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            Cookie cookie = CookieUtil.getCookie(request, "autoLogin");
            if (cookie != null) {//浏览器写到了自动登录Cookie
                String[] values=cookie.getValue().split("&");
                String name = values[0];
                String password = values[1];
                user = userService.login(name, password);
                if (user != null) {
                    session.setAttribute("user", user);
                    List<Auth> authList = authService.selectByRole(user.getRole());
                    session.setAttribute("authList", authList);
                    return true;
                }
            }
            //没有登录，跳转到登录界面
            response.sendRedirect("/page/login");
            return false;
        }
        //已经登录，放行
        return true;
    }*/
   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
       //得到令牌验证
       String token=request.getHeader("Authorization");
       try {
           //验证token
           Map<String,Object> map= JwtUtil.parseToken(token);
           //把token里面的payload存放进去
           ThreadLocalUtil.set(map);
           //放行
           return true;
       } catch (Exception e) {
           //http响应的状态码改为401
           response.setStatus(401);
           //不放行
           return false;
       }
   }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空
        ThreadLocalUtil.remove();
    }
}

